import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:location/location.dart';
import '../data/love_quotes.dart';
import '../models/anniversary.dart';
import '../services/storage_service.dart';
import '../services/weather_service.dart';
import 'package:geolocator/geolocator.dart';
import '../widgets/countdown_widget.dart';
import '../widgets/location_sharing_widget.dart';

class DashboardPage extends StatefulWidget {
  const DashboardPage({Key? key}) : super(key: key);

  @override
  _DashboardPageState createState() => _DashboardPageState();
}

class _DashboardPageState extends State<DashboardPage> with AutomaticKeepAliveClientMixin {
  final StorageService _storageService = StorageService();
  final WeatherService _weatherService = WeatherService();
  final Location _location = Location();

  List<Anniversary> _anniversaries = [];
  DateTime? _relationshipStartDate= new DateTime(2025, 2, 3);
  String _currentTime = '';
  String _greeting = '';
  String _loveQuote = '';
  WeatherInfo? _weatherInfo;
  Timer? _timer;
  bool _isLoading = true;
  bool _isLoadingWeather = true;

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();
    _loadData();
    _updateTime();
    _updateLoveQuote();
    _fetchWeather();

    // 设置定时器，每分钟更新一次时间
    _timer = Timer.periodic(const Duration(minutes: 1), (timer) {
      _updateTime();
    });

    // 每小时更新一次天气
    Timer.periodic(const Duration(hours: 1), (timer) {
      _fetchWeather();
    });

    // 每天更新一次情话
    Timer.periodic(const Duration(hours: 24), (timer) {
      _updateLoveQuote();
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _loadData() async {
    final startDate = await _storageService.getRelationshipStartDate();
    final anniversaries = await _storageService.getAnniversaries();

    setState(() {
      _relationshipStartDate =new DateTime(2025, 2, 3);
      _anniversaries = anniversaries;
      _isLoading = false;
    });
  }

  void _updateTime() {
    final now = DateTime.now();
    final formatter = DateFormat('HH:mm');
    final formattedTime = formatter.format(now);

    String greeting;
    final hour = now.hour;

    if (hour >= 5 && hour < 12) {
      greeting = '早上好';
    } else if (hour >= 12 && hour < 14) {
      greeting = '中午好';
    } else if (hour >= 14 && hour < 18) {
      greeting = '下午好';
    } else if (hour >= 18 && hour < 22) {
      greeting = '晚上好';
    } else {
      greeting = '夜深了';
    }

    setState(() {
      _currentTime = formattedTime;
      _greeting = greeting;
    });
  }

  void _updateLoveQuote() {
    setState(() {
      _loveQuote = LoveQuotes.getRandomQuote();
    });
  }

  Future<Position> _getCurrentLocation() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 位置服务未启用，可以提示用户或请求开启
      return Future.error('Location services are disabled.');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // 永久拒绝，只能引导用户去设置中开启
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // 获取当前位置
    return await Geolocator.getCurrentPosition();
  }

  Future<void> _fetchWeather() async {
    setState(() {
      _isLoadingWeather = true;
    });
print('村上春树');
    try {
      bool serviceEnabled = await _location.serviceEnabled();
      if (!serviceEnabled) {
        serviceEnabled = await _location.requestService();
        if (!serviceEnabled) {
          setState(() {
            _isLoadingWeather = false;
          });
          return;
        }
      }
      print('村上春树1');
      PermissionStatus permissionGranted = await _location.hasPermission();
      if (permissionGranted == PermissionStatus.denied) {
        permissionGranted = await _location.requestPermission();
        if (permissionGranted != PermissionStatus.granted) {
          setState(() {
            _isLoadingWeather = false;
          });
          return;
        }
      }
      print('村上春树2');
      Position position = await _getCurrentLocation();
      // final locationData = await _location.getLocation();
      print('村上春树31');
      final weatherInfo = await _weatherService.getWeather(
        position.latitude!,
        position.longitude!,
      );
      print('村上春树3');
      setState(() {
        _weatherInfo = weatherInfo;
        _isLoadingWeather = false;
      });
    } catch (e) {
      print('获取天气信息失败: $e');
      setState(() {
        _isLoadingWeather = false;
      });
    }
  }

  Future<void> _setRelationshipStartDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _relationshipStartDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
    );

    if (picked != null) {
      await _storageService.setRelationshipStartDate(picked);
      setState(() {
        _relationshipStartDate = picked;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用
    final primaryColor = Theme.of(context).primaryColor;

    if (_isLoading) {
      return const Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return Scaffold(
      backgroundColor: Colors.transparent,
      body: SafeArea(
        child: RefreshIndicator(
          onRefresh: () async {
            await _loadData();
            await _fetchWeather();
            _updateLoveQuote();
          },
          child: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 顶部问候语和时间
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '$_greeting，小苗',
                            style: const TextStyle(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Text(
                            '你笑起来的样子好美，要天天开心啊',
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                      IconButton(
                        icon: const Icon(Icons.settings),
                        onPressed: () {
                          // 导航到设置页面
                        },
                      ),
                    ],
                  ),

                  const SizedBox(height: 24),

                  // 情话卡片
                  Card(
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Icon(Icons.favorite, color: primaryColor),
                              const SizedBox(width: 8),
                              const Text(
                                '今日情话',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const Spacer(),
                              IconButton(
                                icon: const Icon(Icons.refresh),
                                onPressed: _updateLoveQuote,
                                tooltip: '换一句',
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Text(
                            _loveQuote,
                            style: const TextStyle(
                              fontSize: 16,
                              fontStyle: FontStyle.italic,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    ),
                  ),

                  const SizedBox(height: 24),

                  // 在一起的天数
                  GestureDetector(
                    onTap: _setRelationshipStartDate,
                    child: Card(
                      elevation: 2,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(20.0),
                        child: Column(
                          children: [
                            const Text(
                              '我们在一起',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 16),
                            Text(
                              '${DateTime.now().difference(_relationshipStartDate!).inDays}',
                              style: TextStyle(
                                fontSize: 48,
                                fontWeight: FontWeight.bold,
                                color: primaryColor,
                              ),
                            ),
                            const Text(
                              '天',
                              style: TextStyle(fontSize: 16),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              '从 ${DateFormat('yyyy年MM月dd日').format(_relationshipStartDate!)} 开始',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(height: 24),

                  // 天气信息
                  Card(
                    elevation: 2,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: _isLoadingWeather
                          ? const Center(
                        child: Padding(
                          padding: EdgeInsets.all(24.0),
                          child: Text(
                            '我喜欢你小苗',
                            style: TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      )
                          : Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Icon(Icons.wb_sunny, color: primaryColor),
                                  const SizedBox(width: 8),
                                  Text(
                                    '${_weatherInfo?.city ?? "当前城市"}天气',
                                    style: const TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                              IconButton(
                                icon: const Icon(Icons.refresh),
                                onPressed: _fetchWeather,
                                tooltip: '刷新天气',
                              ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    '${_weatherInfo?.temperature.toStringAsFixed(1) ?? "25.0"}°C',
                                    style: const TextStyle(
                                      fontSize: 36,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  Text(
                                    _weatherInfo?.condition ?? "晴",
                                    style: TextStyle(
                                      fontSize: 16,
                                      color: Colors.grey[600],
                                    ),
                                  ),
                                ],
                              ),
                              if (_weatherInfo != null)
                                Image.network(
                                  _weatherInfo!.iconUrl,
                                  width: 80,
                                  height: 80,
                                  errorBuilder: (context, error, stackTrace) {
                                    return Icon(
                                      Icons.wb_sunny,
                                      size: 60,
                                      color: primaryColor,
                                    );
                                  },
                                ),
                            ],
                          ),
                          const SizedBox(height: 16),
                          const Divider(),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Icon(Icons.checkroom, color: primaryColor),
                              const SizedBox(width: 8),
                              const Text(
                                '穿衣建议',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Text(
                            _weatherInfo?.clothingSuggestion ?? '天气舒适，建议穿薄长袖或短袖搭配外套，裤装为宜。',
                            style: const TextStyle(fontSize: 14),
                          ),
                        ],
                      ),
                    ),
                  ),

                  const SizedBox(height: 24),

                  // 倒数日部分
                  // Row(
                  //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  //   children: [
                  //     Text(
                  //       '重要日子',
                  //       style: Theme.of(context).textTheme.headline6,
                  //     ),
                  //     TextButton.icon(
                  //       onPressed: () {
                  //         // 导航到添加纪念日页面
                  //       },
                  //       icon: Icon(Icons.add, color: primaryColor),
                  //       label: const Text('添加'),
                  //     ),
                  //   ],
                  // ),
                  // const SizedBox(height: 8),
                  // SizedBox(
                  //   height: 120,
                  //   child: _anniversaries.isEmpty
                  //       ? Center(
                  //     child: Text(
                  //       '还没有重要日子，点击添加',
                  //       style: TextStyle(color: Colors.grey[600]),
                  //     ),
                  //   )
                  //       : ListView.builder(
                  //     scrollDirection: Axis.horizontal,
                  //     itemCount: _anniversaries.length,
                  //     itemBuilder: (context, index) {
                  //       return CountdownWidget(anniversary: _anniversaries[index]);
                  //     },
                  //   ),
                  // ),
                  //
                  // const SizedBox(height: 24),
                  //
                  // // 位置共享部分
                  // const LocationSharingWidget(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

